<template>
    <div class="log-manage">
        <!-- 面包屑和标题 -->
        <el-breadcrumb separator="/" class="mb-2">
            <el-breadcrumb-item>系统管理</el-breadcrumb-item>
            <el-breadcrumb-item>操作日志</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="page-title">操作日志</div>

        <!-- 查询区 -->
        <el-form :inline="true" :model="query" class="query-form">
            <el-form-item>
                <el-input v-model="query.userName" placeholder="用户名" clearable style="width: 220px;" />
            </el-form-item>
            <el-form-item>
                <el-select :v-model="query.isSuccess " placeholder="操作状态" clearable style="width: 150px;">
                    <el-option label="成功" :value="true" />
                    <el-option label="失败" :value="false" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-select v-model="query.isModule" placeholder="模块类型" clearable style="width: 150px;">
                    <el-option label="用户管理" value="user" />
                    <el-option label="角色管理" value="role" />
                    <el-option label="部门管理" value="department" />
                    <el-option label="会议管理" value="meeting" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-date-picker v-model="query.timeRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                    end-placeholder="结束日期" style="width: 280px;" value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch">查询</el-button>
                <el-button @click="onReset">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 操作区 -->
        <div class="toolbar mb-2">
            <el-button @click="refreshLog">刷新</el-button>
            <el-button @click="onExport">导出数据</el-button>
        </div>

        <!-- 日志表格 -->
        <el-table :data="tableData" border stripe style="width: 100%" v-loading="loading">
            <el-table-column type="index" label="序号" width="80" />
            <el-table-column prop="MethodName" label="操作方法" min-width="200" />
            <el-table-column prop="IsSuccess" label="操作状态" width="100">
                <template #default="scope">
                    <el-tag :type="scope.row.IsSuccess ? 'success' : 'danger'">
                        {{ scope.row.IsSuccess ? '成功' : '失败' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="UserId" label="用户ID" width="100" />
            <el-table-column prop="UserName" label="用户名" min-width="120" />
            <el-table-column prop="IsModule" label="模块类型" min-width="120" />
            <el-table-column prop="IsType" label="操作类型" min-width="120" />
            <el-table-column prop="OperationTime" label="操作时间" min-width="180" />
            <el-table-column prop="Description" label="操作描述" min-width="200" show-overflow-tooltip />
            <el-table-column label="操作" width="120" fixed="right">
                <template #default="scope">
                    <el-button type="primary" plain @click="viewDetail(scope.row)">详情</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
                :page-size="query.pageSize" :current-page="query.pageIndex" :page-sizes="[10, 20, 50, 100]"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 详情弹窗 -->
        <el-dialog v-model="detailDialog.visible" :title="'操作日志详情'" width="70%">
            <div class="log-detail">
                <el-descriptions :column="2" border>
                    <el-descriptions-item label="操作方法">{{ detailDialog.data.MethodName }}</el-descriptions-item>
                    <el-descriptions-item label="操作状态">
                        <el-tag :type="detailDialog.data.IsSuccess ? 'success' : 'danger'">
                            {{ detailDialog.data.IsSuccess ? '成功' : '失败' }}
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="用户ID">{{ detailDialog.data.UserId }}</el-descriptions-item>
                    <el-descriptions-item label="用户名">{{ detailDialog.data.UserName }}</el-descriptions-item>
                    <el-descriptions-item label="模块类型">{{ detailDialog.data.IsModule }}</el-descriptions-item>
                    <el-descriptions-item label="操作类型">{{ detailDialog.data.IsType }}</el-descriptions-item>
                    <el-descriptions-item label="操作时间">{{ detailDialog.data.OperationTime }}</el-descriptions-item>
                    <el-descriptions-item label="操作描述">{{ detailDialog.data.Description }}</el-descriptions-item>
                </el-descriptions>

                <div class="error-container" v-if="detailDialog.data.ErrorMessage">
                    <h3 class="error-title">错误信息</h3>
                    <el-alert type="error" :closable="false">
                        <pre class="error-message">{{ detailDialog.data.ErrorMessage }}</pre>
                    </el-alert>
                </div>
            </div>
            <template #footer>
                <el-button @click="detailDialog.visible = false">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getOperationLogs,exportOperationLogs } from '@/api/system'

// 日志项接口
interface OperationLogItem {
    MethodName: string;
    IsSuccess: boolean;
    UserId: string;
    UserName: string;
    OperationTime: string;
    Description: string;
    ErrorMessage: string;
    IsModule: string;
    IsType: string;
}

// 查询参数
const query = reactive({
    pageIndex: 1,
    pageSize: 10,
    userName: '',
    isSuccess: null as boolean | null,
    isModule: '',
    timeRange: [] as string[]
})

// 表格数据
const tableData = ref<OperationLogItem[]>([])
const loading = ref(false)
const total = ref(0)

// 详情弹窗控制
const detailDialog = reactive({
    visible: false,
    data: {} as OperationLogItem
})

// 获取日志数据
const fetchLogData = async () => {
    loading.value = true

    try {
        // 处理查询参数
        const params: any = {
            pageIndex: query.pageIndex,
            pageSize: query.pageSize
        }

        if (query.userName) {
            params.userName = query.userName
        }

        if (query.isSuccess !== null) {
            params.isSuccess = query.isSuccess
        }

        if (query.isModule) {
            params.isModule = query.isModule
        }

        if (query.timeRange && query.timeRange.length === 2) {
            params.startTime = query.timeRange[0]
            params.endTime = query.timeRange[1]
        }

        // 调用API获取日志数据
        const response = await getOperationLogs(params) as any

            tableData.value = response.Data.Data || []
            total.value = response.Data.TotalCount || 0
            console.log('获取到的日志数据:', tableData.value)
    } catch (error: any) {
        console.error('获取日志数据失败:', error)
        ElMessage.error(error.message || '获取日志数据失败')
        tableData.value = []
        total.value = 0
    } finally {
        loading.value = false
    }
}

///导出用户信息
const onExport = async () => {
    try {
        const response = await exportOperationLogs();

        // 创建Blob对象
        const blob = new Blob([response.data], {
            type: response.headers['content-type']
        });

        // 从响应头中获取文件名，如果没有则使用默认名称
        let filename = 'logs_export.xlsx';
        const contentDisposition = response.headers['content-disposition'];
        if (contentDisposition) {
            const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
            if (filenameMatch && filenameMatch[1]) {
                filename = filenameMatch[1].replace(/['"]/g, '');
            }
        }

        // 创建下载链接并模拟点击
        const downloadLink = document.createElement('a');
        downloadLink.href = URL.createObjectURL(blob);
        downloadLink.download = filename;
        document.body.appendChild(downloadLink);
        downloadLink.click();

        // 清理
        document.body.removeChild(downloadLink);
        URL.revokeObjectURL(downloadLink.href);

        ElMessage.success('导出成功');
    } catch (error) {
        console.error('导出失败:', error);
        ElMessage.error('导出失败，请稍后重试');
    }
}

// 刷新日志
const refreshLog = () => {
    fetchLogData()
    ElMessage.success('日志已刷新')
}

// 搜索
const onSearch = () => {
    query.pageIndex = 1
    fetchLogData()
}

// 重置
const onReset = () => {
    query.pageIndex = 1
    query.userName = ''
    query.isSuccess = null
    query.isModule = ''
    query.timeRange = []
    fetchLogData()
}

// 查看详情
const viewDetail = (row: OperationLogItem) => {
    detailDialog.data = { ...row }
    detailDialog.visible = true
}

// 分页大小变化
const handleSizeChange = (size: number) => {
    query.pageSize = size
    fetchLogData()
}

// 页码变化
const handleCurrentChange = (page: number) => {
    query.pageIndex = page
    fetchLogData()
}

// 组件挂载时加载数据
onMounted(fetchLogData)
</script>

<style scoped>
.log-manage {
    background: #fff;
    border-radius: 8px;
    padding: 12px;
    min-height: 600px;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
    width: 100%;
}

.page-title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 12px;
}

.query-form {
    margin-bottom: 16px;
}

.toolbar {
    margin-bottom: 16px;
}

.mb-2 {
    margin-bottom: 12px;
}

.pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

.log-detail {
    margin-bottom: 20px;
}

.error-container {
    margin-top: 20px;
}

.error-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
    color: #f56c6c;
}

.error-message {
    font-family: monospace;
    white-space: pre-wrap;
    word-break: break-all;
    font-size: 12px;
    line-height: 1.5;
    max-height: 300px;
    overflow-y: auto;
    padding: 10px;
    margin: 0;
}
</style>